package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author: Rodgers
 * @Date 2022/3/15 9:45
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    //处理用户端登录请求
    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map, HttpSession session){
        //1.接收数据封装到Map
        String phone = map.get("phone"); //输入的手机号
        String code = map.get("code"); //用户输入的验证码

        //2.从session中获取存储的验证码
        String sessionCode = (String) session.getAttribute(phone);

        //3.调用业务层进行登录操作，返回登录的用户对象
        User loginUser = userService.login(phone,code,sessionCode);
        if (loginUser!=null){
            //4.登录用户有效，写入用户的id到session里
            session.setAttribute("user",loginUser.getId());
            //登录成功后，session的验证码就可以删除了
            session.removeAttribute(phone);

            return R.success(loginUser);
        }

        return R.error("登录失败");
    }

    @RequestMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session){
        //1.接收手机号封装User对象
        //2.生成4位手机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码："+code);

        //3.发送手机验证码
        //4.将生成的验证码存储到session中
        session.setAttribute(user.getPhone(),code);
        return R.success("发送验证码短信成功");
    }
}
